﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Comissoes.JQGridObject;
using Comissoes.Models;
using System.Web;

namespace Comissoes.Controllers
{
    public class LojasController : AppController
    {
        private xcontEntities db = new xcontEntities();

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult LojasLookupList()
        {
            return Json((from c in db.LOJAS.Include("PESSOAS").ToList() where c.PESSOAS.NOME_PESSOA.ToUpper().Contains(Request["term"].ToUpper()) select new { value = c.PESSOAS.NOME_PESSOA, label = c.PESSOAS.NOME_PESSOA, id = c.COD_LOJA }).Take(10), JsonRequestBehavior.AllowGet);
        }
        
        public JsonResult List(String sidx, String sord, Int32 page, Int32 rows, Boolean _search, String searchField, String searchString, String searchOper)
        {
            try
            {
                var q = from c in db.LOJAS
                        select new
                        {
                            c.COD_LOJA,
                            c.NOME_LOJA,
                            c.REGIMES_TRIBUTARIOS.DESC_RGTR,
                            ATIVO_LOJA = c.ATIVO_LOJA == "A" ? "Sim" : "Não"
                        };

                JQGridBuilder jbuilder = new JQGridBuilder(q.AsQueryable(), page, sidx, sord, searchField, searchString, searchOper, "COD_LOJA", _search, rows);

                return Json(jbuilder.GetObject(), JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult Details(int id)
        {
            return View(db.LOJAS.Include("PESSOAS").Include("REGIMES_TRIBUTARIOS").FirstOrDefault(t => t.COD_LOJA == id));
        }

        public ActionResult Edit(Int32? id)
        {
            LojasModel loja = new LojasModel(id);

            ViewData["IDRGTR"] = new SelectList(db.REGIMES_TRIBUTARIOS, "ID_RGTR", "DESC_RGTR", loja.loja.REGIMES_TRIBUTARIOS.ID_RGTR);

            return View(loja);
        }

        [HttpPost]
        public ActionResult Edit(Int32? id, FormCollection form)
        {
            LojasModel loja = new LojasModel(id);

            if (loja.UpdateValidate(form).Any())
                return Json(loja.UpdateValidate(form), JsonRequestBehavior.AllowGet);

            else
                loja.Update(form);

            return Json(loja.loja.COD_LOJA, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Delete(int id)
        {
            List<string> erros = new List<string>();
            try
            {
                db.DeleteObject(db.LOJAS.FirstOrDefault(t => t.COD_LOJA == id));
                db.SaveChanges();

                return Json(true, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                erros.Add(ex.Message);
                if (ex.InnerException != null)
                    erros.Add(ex.InnerException.Message);
            }

            return Json(erros, JsonRequestBehavior.AllowGet);
        }
        
        public JsonResult Cnaes(String sidx, String sord, Int32 page, Int32 rows, Boolean _search, String searchOper, String DESC_CNAE, String COD_CNAE, Int32 COD_LOJA)
        {
            try
            {
                var q = from c in db.CNAES_LOJA.Include("CNAES").Include("LOJAS").ToList()
                        where (c.CNAES.SUBCLASSE_CNAE.HasValue)
                        && (c.LOJAS.COD_LOJA == COD_LOJA)
                        select new
                        {
                            act = "",
                            c.ID_CNLJ,
                            COD_CNAE = c.CNAES.DIVISAO_CNAE.ToString().PadLeft(2, '0') + c.CNAES.GRUPO_CNAE.ToString().PadLeft(2, '0') + "-" + c.CNAES.CLASSE_CNAE + "/" + c.CNAES.SUBCLASSE_CNAE.ToString().PadLeft(2, '0'),
                            c.CNAES.DESC_CNAE
                        };

                String searchField = string.IsNullOrEmpty(DESC_CNAE) ? "COD_CNAE" : "DESC_CNAE";
                String searchString = string.IsNullOrEmpty(DESC_CNAE) ? COD_CNAE : DESC_CNAE;

                JQGridBuilder jbuilder = new JQGridBuilder(q.AsQueryable(), page, sidx, sord, searchField, searchString, searchOper, "ID_CNLJ", _search, rows);

                return Json(jbuilder.GetObject(), JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult CnaeUpdate(Int32 ID_CNAE, Int32 COD_LOJA)
        {
            List<string> erros = new List<string>();

            try
            {
                if (!db.CNAES_LOJA.Any(t => t.LOJAS.COD_LOJA == COD_LOJA && t.CNAES.ID_CNAE == ID_CNAE))
                {
                    db.AddToCNAES_LOJA(new CNAES_LOJA
                    {
                        CNAES = db.CNAES.FirstOrDefault(t => t.ID_CNAE == ID_CNAE),
                        LOJAS = db.LOJAS.FirstOrDefault(t => t.COD_LOJA == COD_LOJA)
                    });
                    db.SaveChanges();
                }

                return Json(new { result = true }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                erros.Add(ex.Message);
                if (ex.InnerException != null)
                    erros.Add(ex.InnerException.Message);
            }

            return Json(new { result = false, erros = erros }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult CnaeDelete(Int32 id)
        {
            List<string> erros = new List<string>();

            try
            {
                db.DeleteObject(db.CNAES_LOJA.FirstOrDefault(t => t.ID_CNLJ == id));
                db.SaveChanges();

                return Json(new { result = true }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                erros.Add(ex.Message);
                if (ex.InnerException != null)
                    erros.Add(ex.InnerException.Message);
            }

            return Json(new { result = false, erros = erros }, JsonRequestBehavior.AllowGet);
        }

        // Monta a lista de tipos de produtos
        public JsonResult Listas(String sidx, String sord, Int32 page, Int32 rows, Boolean _search, String DESC_LISTA, String COD_LISTA, String searchOper,Int32 COD_LOJA)
        {
            try
            {
                var q = from c in db.LISTAS_LOJA
                        where c.LOJAS.COD_LOJA == COD_LOJA
                        select new
                        {
                            act = "",
                            c.ID_LSLJ,
                            c.LISTAS.COD_LISTA,
                            c.LISTAS.DESC_LISTA
                        };

                String searchField = string.IsNullOrEmpty(DESC_LISTA) ? "COD_LISTA" : "DESC_LISTA";
                String searchString = string.IsNullOrEmpty(DESC_LISTA) ? COD_LISTA : DESC_LISTA;

                JQGridBuilder jbuilder = new JQGridBuilder(q, page, sidx, sord, searchField, searchString, searchOper, "ID_LSLJ", _search, rows);

                return Json(jbuilder.GetObject(), JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult ListaUpdate(Int32 COD_LISTA, Int32 COD_LOJA)
        {
            List<string> erros = new List<string>();

            try
            {
                if (!db.LISTAS_LOJA.Any(t => t.LOJAS.COD_LOJA == COD_LOJA && t.LISTAS.COD_LISTA == COD_LISTA))
                {
                    db.AddToLISTAS_LOJA(new LISTAS_LOJA
                    {
                        LISTAS = db.LISTAS.FirstOrDefault(t => t.COD_LISTA == COD_LISTA),
                        LOJAS = db.LOJAS.FirstOrDefault(t => t.COD_LOJA == COD_LOJA)
                    });
                    db.SaveChanges();
                }

                return Json(new { result = true }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                erros.Add(ex.Message);
                if (ex.InnerException != null)
                    erros.Add(ex.InnerException.Message);
            }

            return Json(new { result = false, erros = erros }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ListaDelete(Int32 id)
        {
            List<string> erros = new List<string>();

            try
            {
                db.DeleteObject(db.LISTAS_LOJA.FirstOrDefault(t => t.ID_LSLJ == id));
                db.SaveChanges();

                return Json(new { result = true }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                erros.Add(ex.Message);
                if (ex.InnerException != null)
                    erros.Add(ex.InnerException.Message);
            }

            return Json(new { result = false, erros = erros }, JsonRequestBehavior.AllowGet);
        }
    }
}
